package base.widgets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.redr.canvas.OSPath;
import org.redr.canvas.RRW;
import org.redr.canvas.RedRApplication;
import org.redr.canvas.SignalClass;
import org.redr.widgetGUI.core.CheckBox;
import org.redr.widgetGUI.core.ComboBox;
import org.redr.widgetGUI.core.CommitButton;
import org.redr.widgetGUI.core.WidgetBox;
import org.redr.widgetGUI.settings.WidgetSettings;
import org.redr.widgetGUI.settings.settingsTools.ItemsHandler;
import org.rosuda.REngine.REXPVector;

import base.signals.RDataFrame;
import base.signals.RDataFrameInput;
import base.signals.RDataFrameOutput;

public class Sort extends RRW{
		public static final String name = "Sort";
		public static final String summary = "Sorts data from a table";
		public static final String details = "Sorts data from a table";
		public static final String icon = OSPath.join(RedRApplication.parentDir, "coreIcons", "default.png").getAbsolutePath();
	    private ComboBox sortingColumn1;
		private ComboBox sortingColumn2;
		private ComboBox sortingColumn3;
		private CommitButton commitButton;
		private CheckBox options;
		private String inputData;
		private RDataFrame x;
		
		public Sort(WidgetSettings w) {
			super(w);
			// TODO Auto-generated constructor stub
		
		}
	    /*
		def __init__(self, **kwargs):
	        OWRpy.__init__(self, **kwargs)
	        self.setRvariableNames(["sort"])
	        self.data = {}
	         
	        self.RFunctionParam_x = ''
	        
	    def commitFunction(self):
	        if unicode(self.RFunctionParam_x) == '': return
	        if self.sortingColumn1.currentText() =='':
	            return
	        injection = []

	        injection.append('%s$%s' % (self.RFunctionParam_x, self.sortingColumn1.currentText()))
	        if self.sortingColumn2.currentText() !='':
	            injection.append('%s$%s' % (self.RFunctionParam_x, self.sortingColumn2.currentText()))
	        if self.sortingColumn3.currentText() !='':
	            injection.append('%s$%s' % (self.RFunctionParam_x, self.sortingColumn3.currentText()))
	            
	            
	        if _('Decreasing') in self.options.getChecked():
	            string = 'decreasing=TRUE'
	            injection.append(string)
	        else:
	            injection.append('decreasing = FALSE')
	        if _('NA Last') in self.options.getChecked():
	            injection.append('na.last = TRUE')
	        inj = ','.join(injection)

	        self.R('%s<-%s[order(%s),]' % (self.Rvariables['sort'], self.RFunctionParam_x, inj), wantType = 'NoConversion')
	        newData = signals.base.RDataFrame(self, data = self.Rvariables["sort"]) 
	        
	        self.rSend("id0", newData)

	        */
		@Override
		protected void initGUI() {
			// TODO Auto-generated method stub
			WidgetBox standardTab = new WidgetBox(gui, settings.getSettings("standardBox"));
			
			WidgetSettings optionSettings = (WidgetSettings) settings.getSettings("options")
					.setSetting("label", _("Options"));
			ItemsHandler buttonSettings = optionSettings.items("buttons");
			buttonSettings.addItem("decreasing", _("Decreasing"));
			buttonSettings.addItem("nalast", _("NA Last"));
			
			options = new CheckBox(gui, optionSettings);
			
			sortingColumn1 = new ComboBox(standardTab, (WidgetSettings) settings.getSettings("sortColumn1")
					.setSetting("label", _("First Column to Sort:")));
			sortingColumn2 = new ComboBox(standardTab, (WidgetSettings) settings.getSettings("sortColumn2")
					.setSetting("label", _("Second Column to Sort:")));
			sortingColumn3 = new ComboBox(standardTab, (WidgetSettings) settings.getSettings("sortColumn3")
					.setSetting("label", _("Third Column to Sort:")));
			
			commitButton = new CommitButton(gui.bottomAreaRight, (WidgetSettings) settings.getSettings("commitButton")
					.setSetting("label", _("Commit")));
			
		}
		

		@Override
		protected void initSignals() {
			// TODO Auto-generated method stub
			// addInput("id0", _("Data Table"), RDataFrame.class, false);
			// addOutput("id0", _("Sorted Data Table"), RDataFrame.class);
	        this.addInput(new RDataFrameInput(this, "id0", _("Data Table"), false));
	        this.addOutput(new RDataFrameOutput(this, "id0", _("Sorted Data Table")));
		}
		@Override
		protected void dataInput(String id, Object data, String widgetId) {
			// TODO Auto-generated method stub
			System.out.println("dataInput triggered!!!");
			try {
				if (id.equals("id0")){
					x = (RDataFrame) data;
					if (data != null){
						inputData = (String) data;
						REXPVector colnames = (REXPVector) R(String.format("colnames(%s)", inputData));
						HashMap<String, String> names = new HashMap<String, String>();
						names.put("", "");
						for (String s : colnames.asStrings()){
							names.put(s, s);
						}
						sortingColumn1.update(names);
						sortingColumn2.update(names);
						sortingColumn3.update(names);
						if (commitButton.processOnInput()){
							commitFunction();
						}
					}
						
				}	
			}  catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
		}
		
		public void commitFunction(){
			if (x == null) return;
			if (sortingColumn1.currentId().equals("")) return;
			
			List<String> injection = new ArrayList<String>();
			injection.add(String.format("%s$%s", x.getData(), sortingColumn1.currentId()));
			
			if (sortingColumn2.currentText().equals("")) injection.add(String.format("%s$%s", x.getData(), sortingColumn2.currentId()));
			if (sortingColumn2.currentText().equals("")) injection.add(String.format("%s$%s", x.getData(), sortingColumn3.currentId()));
			
			String decreasing = "decreasing=FALSE";
			if (options.checkedButtons().contains(_("Decreasing"))) decreasing = "decresing=TRUE";
			injection.add(decreasing);
			
			if (options.checkedButtons().contains(_("NA Last"))) injection.add("na.last=TRUE");
			
			String inj = StringUtils.join(injection, ",");
			
			try {
				R(String.format("%s<-%s[order(%s),]", "tempSort", x.getData(), inj));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			/*
			        self.R('%s<-%s[order(%s),]' % (self.Rvariables['sort'], self.RFunctionParam_x, inj), wantType = 'NoConversion')
			        newData = signals.base.RDataFrame(self, data = self.Rvariables["sort"]) 
			        
			        self.rSend("id0", newData)
			*/
		}
		@Override
		protected void initVariables() {
			// TODO Auto-generated method stub
			
		}
}
